package com.wedo.mall.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.widget.TextView;

import com.e.library.dialog.EDialog;
import com.e.library.listener.EListener;
import com.wedo.mall.R;

import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

/**
 * 设置支付密码
 * Created by e on 2017/9/21.
 */
public class InputPasswordDialog extends EDialog {

    @BindView(R.id.tv_title) TextView tv_title;
    @BindViews({R.id.tv_pw1,R.id.tv_pw2,R.id.tv_pw3,R.id.tv_pw4,R.id.tv_pw5,R.id.tv_pw6}) List<TextView> pws;

    private StringBuilder password = new StringBuilder();
    private EListener<String> listener;

    public InputPasswordDialog(Context context) {
        super(context);
    }

    @Override
    protected int layout() {
        return R.layout.dialog_pay_password;
    }

    @Override
    protected void onDialogCreated(Context context) {
        tv_title.setText(R.string.order_pay_password);
    }

    @OnClick(R.id.iv_delete)
    protected void onDeleteClick(){
        if (TextUtils.isEmpty(password)){
            return;
        }
        password.deleteCharAt(password.length()-1);
        onTextChanged(password);
    }

    @OnClick({R.id.tv_number0,R.id.tv_number1,R.id.tv_number2,R.id.tv_number3,
            R.id.tv_number4,R.id.tv_number5,R.id.tv_number6,R.id.tv_number7
            ,R.id.tv_number8,R.id.tv_number9})
    protected void onNumberClick(TextView tv){
        String input = tv.getText().toString().trim();
        if (this.password.length() !=6){
            this.password.append(input);
            onTextChanged(this.password);
            if (this.password.length() == 6){
                if (listener !=null){
                    listener.onInvoked(null,password.toString(),0);
                }
                dismiss();
            }
        }
    }

    private void onTextChanged(StringBuilder sb){
        clear();
        int length = sb.length();
        for (int i= 0;i<length;i++){
            char c= sb.charAt(i);
            pws.get(i).setText(String.valueOf(c));
        }
    }

    private void clear(){
        for (TextView tv:pws){
            tv.setText("");
        }
    }

    public void setListener(EListener<String> listener){
        this.listener = listener;
    }
}
